<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
    destroyOnClose
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, useAttrs } from "vue";
import { BasicForm, useForm } from "/src/components/Form";
import { BasicDrawer, useDrawerInner } from "/src/components/Drawer";
import { BasicTree, TreeItem } from "/src/components/Tree";
import { formSchema } from "./index.data";
import { add, edit } from "./index.api";
import { useSuccess } from "/@/hooks/rw/handleSuccess";
const { rhandleSuccess } = useSuccess();
// 声明Emits
const emit = defineEmits(["success", "register"]);
const attrs = useAttrs();
const isUpdate = ref(true);
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 90,
  schemas: formSchema,
  showActionButtonGroup: false,
});
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  isUpdate.value = !!data?.isUpdate;
  setDrawerProps({ confirmLoading: false });
  if (unref(isUpdate)) {
    setFieldsValue({
      ...data.record,
    });
  }
  //禁用表单
  setProps({ disabled: !attrs.showFooter });
});
/**
 * 标题
 */
const getTitle = computed(() => (!unref(isUpdate) ? "发布消息" : "编辑消息"));
/**
 * 提交
 */
async function handleSubmit() {
  try {
    const values = await validate();
    let res;
    setDrawerProps({ confirmLoading: true });
    //提交表单
    if (isUpdate.value) {
      res = await edit(values.id, values);
    } else {
      res = await add(values);
    }
    rhandleSuccess(res, () => {});
    closeDrawer();
    emit("success");
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
